<template>
  <!-- 发端数据详情 -->
  <div class="start-data-container">
    <!-- 审核/编辑/详情 对话框 -->
    <el-dialog :title="title" v-model="dialogVisiable" :width="`${dynamic.dialogWidth}`" append-to-body
      :close-on-press-escape="preview_image_mask ? false : true">
      <!-- 图片显示区域 -->
      <div :style="displayStatus" class="dy-dialog">
        <div class="demo-image__lazy" :style="backgroundStyle">
          <el-image style="width: 100%;height: 100%; border-radius: 4px" :src="dialogPreviewUrl"
            :preview-src-list="[dialogPreviewUrl]" hide-on-click-modal preview-teleported
            @close="preview_image_mask = false" @show="preview_image_mask = true">
            <template #error>
              <div class="image-slot" style="font-size: 20px">
                未上传
              </div>
            </template>
          </el-image>
        </div>

        <!-- 详情表单区域 -->
        <div class="dy-form">
          <!-- 提示 -->
          <el-form-item v-if="formEdit.railwayAssociated == 1" class="global-tip-container" style="width: 100%;">
            <div class="global-tip">
              <span class="tip-icon"><svg-icon icon-class="light-tip" /></span>
              <div class="tip-content">
                <p>当前运单已完成铁路数据匹配，无法修改箱号以及时间信息</p>
              </div>
            </div>
          </el-form-item>
          <el-form class="form" :model="formEdit" ref="formEditRef" :rules="formEditRules" :style="formStyle"
            label-width="100px">
            <el-form-item label="车牌号：" prop="plateNo" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-model="formEdit.plateNo" class="form-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="司机：" prop="driverName" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-model="formEdit.driverName" class="form-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="线路：" prop="routeName" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-model="formEdit.routeName" class="form-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="货物：" prop="cargo" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-model="formEdit.cargo" class="form-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="发车时间：" prop="departureTime" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-date-picker v-model="formEdit.departureTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" teleported style="width: 100%"
                :disabled="formEdit.railwayAssociated == 1 ? true : false"></el-date-picker>
            </el-form-item>
            <el-form-item label="到达时间：" prop="arrivalTime" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-date-picker v-model="formEdit.arrivalTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" teleported style="width: 100%"
                :disabled="formEdit.railwayAssociated == 1 ? true : false"></el-date-picker>
            </el-form-item>
            <el-form-item label="审核状态：" prop="checked" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-model="formEdit.checked" :value="formEdit.checked == 0 ? '未审核' : '已审核'" class="form-input"
                disabled></el-input>
            </el-form-item>
            <el-form-item label="磅单号：" prop="billNo" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-noSpace v-model="formEdit.billNo" class="form-input" placeholder="请输入磅单号"
                clearable></el-input>
            </el-form-item>
            <el-form-item label="净重：" prop="netWeight" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-noSpace v-model="formEdit.netWeight" class="form-input" placeholder="请输入净重" clearable>
                <template #append>吨</template></el-input>
            </el-form-item>
            <el-form-item label="箱号：" prop="containerNo" class="form-items" :style="`width: ${100 / formColumn}%`">
              <el-input v-noSpace v-model="formEdit.containerNo" class="form-input" placeholder="请输入箱号" clearable
                :disabled="formEdit.railwayAssociated == 1 ? true : false"></el-input>
            </el-form-item>
            <el-form-item label="备注：" prop="checkNotes" class="form-items" style="width: 100%">
              <el-input v-if="formEdit.checkNotes" v-model="formEdit.checkNotes" type="textarea"
                :autosize="{ minRows: 2, maxRows: 7 }" placeholder="请输入备注" maxlength="200" show-word-limit clearable>
              </el-input>
              <el-input v-else v-model="formEdit.checkNotes" type="textarea" :autosize="{ minRows: 2, maxRows: 7 }"
                placeholder="请输入备注" maxlength="200" show-word-limit clearable>
              </el-input>
            </el-form-item>
          </el-form>
          <div class="dy-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onBeforeMount, onMounted, watchEffect, computed, getCurrentInstance } from 'vue';
import { transportInfoApi, updateHaulApi } from "@/api/transportOrderManagement/transportOrderList";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
let $emit = defineEmits(['updateStartRowData']);
const { proxy } = getCurrentInstance();
const route = useRoute();
let title = ref('查看运单')
let preview_image_mask = ref(false)
let dialogVisiable = ref(false);
/** 审核、详情、编辑对话框图片 */
let dialogPreviewUrl = ref('');
/** 审核、详情、编辑对话框图片背景展示状态样式 */
let backgroundStyle = computed(() => {
  return {
    width: dynamic.dynamicWidth == 0 ? '100%' : dynamic.dynamicWidth + 'px', // 根据需要设置宽度
    height: dynamic.dynamicHeight + 'px', // 根据需要设置高度
  };
})
/** 审核、详情、编辑对话框动态背景 */
let dynamic = reactive({
  dialogWidth: 1000,
  dynamicBack: '',
  dynamicWidth: 0,
  dynamicHeight: 0
})
/** 审核、详情、编辑对话框展示样式 */
let displayStatus = reactive({
  display: 'flex',
  flexDirection: '',
})
/** 审核、详情、编辑对话框表单的展示样式 */
let formStyle = reactive({
  display: 'flex',
  flexWrap: 'wrap',
  height: 'max-content',
  width: '',
})
/** 审核、详情、编辑对话框表单的展示列数 */
let formColumn = ref(0)
const data = reactive({
  formEdit: {},
  formEditRules: {
    departureTime: [{ required: true, message: "发车时间不能为空", trigger: "change" }],
    arrivalTime: [{ required: true, message: "到达时间不能为空", trigger: "change" }],
    netWeight: [
      { required: true, message: "净重不能为空", trigger: "blur" },
      { pattern: /^(?!0(\.0+)?$)\d+(\.\d+)?$/, message: '仅允许输入大于0的小数和整数', trigger: 'blur' },
      { pattern: /^(?!0\d)(\d+(\.\d*)?|\.\d+)$/, message: '输入内容不合法', trigger: 'blur' },
    ],
    billNo: [{ required: true, message: "磅单号不能为空", trigger: "blur" }],
    containerNo: [
      { required: true, message: "箱号不能为空", trigger: "blur" },
      // { max: 11, message: "箱号不能超过11位", trigger: "blur" }
    ]
  }
});
const { formEdit, formEditRules } = toRefs(data);
onBeforeMount(() => {
})
onMounted(() => { })
watchEffect(() => {
})
/**
 *  Method
 * 
 */
/** 处理图片回显dialog动态样式 */
function getDyStyle(row) {
  return new Promise((resolve, reject) => {
    getImageSize(`${row.weightBillImgUrl}`, function (size) {
      if (size) {
        const { width, height } = size
        const ImageH = Number(height)
        const ImageW = Number(width)
        getCalcSize(ImageW, ImageH)
        getUnitByColumn(ImageW, ImageH)
      } else {
        const ImageH = Number(1024)
        const ImageW = Number(768)
        getCalcSize(ImageW, ImageH)
        getUnitByColumn(ImageW, ImageH)
      }
      resolve()
    });
  })
}

/** 获取图片尺寸 */
function getImageSize(url, callback) {
  var img = new Image();
  img.onload = function () {
    callback({ width: img.width, height: img.height });
  };
  img.onerror = function () {
    callback(null);
  };
  img.src = url;
}

/** 对话框每列展示formItem个数 */
function getUnitByColumn(w, h) {
  const dynamicW = dynamic.dialogWidth - 60
  if (w > h) {
    formColumn.value = 3
    formStyle.width = dynamicW + 'px'
  } else {
    formColumn.value = 2
    formStyle.width = dynamicW / 2 + 'px'
  }
}

/** 根据图片的的宽度或高度,计算图片的高度或宽度,减去dialog中的40像素padding */
function getCalcSize(w, h) {
  const dynamicW = dynamic.dialogWidth - 60
  if (w > h) {
    displayStatus.flexDirection = 'column ',
      dynamic.dynamicWidth = dynamicW
  } else {
    displayStatus.flexDirection = 'row',
      dynamic.dynamicWidth = dynamicW / 2.8
  }
  dynamic.dynamicHeight = dynamic.dynamicWidth * (h / w)
}

/** 获取审核、详情、编辑对话框动态内容 */
async function getFormData(row) {
  await transportInfo(row.id)
}

/** 打开审核、详情、编辑对话框 */
async function viewData(row, type) {
  // 打开时重置表单
  reset()
  await getFormData(row, type)
  row['weightBillImgUrl'] = dialogPreviewUrl.value
  await getDyStyle(row)
  dialogVisiable.value = true;
};

/** 查询运单详情 */
async function transportInfo(id) {
  await transportInfoApi(id).then(response => {
    if (response.code === 1) {
      formEdit.value = response.data
      dialogPreviewUrl.value = response.data.weightBillImgUrl
      formEdit.value = response.data
      formEdit.value.billNo = response.data.weightBillNo
      formEdit.value.haulId = response.data.id
      delete formEdit.value.weightBillNo
    } else {
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
  })
}



/** 提交表单 */
function submitForm() {
  if (dialogPreviewUrl.value) {
    proxy.$refs["formEditRef"].validate(valid => {
      if (valid) {
        updateHaul()
      }
    })
  } else {
    ElMessage({ message: '未上传磅单!', type: 'error' })
  }
}

/** 提交编辑磅单信息表单 */
function updateHaul() {
  updateHaulApi(formEdit.value).then(response => {
    if (response.code === 1) {
      let { weightBillNo, netWeight, id, containerNo, departureTime, arrivalTime } = response.data
      let newObject = { weightBillNo, netWeight, id, containerNo, departureTime, arrivalTime };
      /** 向父组件发送自定义事件 */
      $emit('updateStartRowData', newObject)
      dialogVisiable.value = false
      ElMessage({ message: '操作成功', type: 'success' })
    } else {
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
  })
}


/** 重置数据以及表单校验规则  */
async function reset() {
  formEdit.value = {
    haulId: undefined,
    plateNo: undefined,
    driverName: undefined,
    routeName: undefined,
    cargo: undefined,
    departureTime: undefined,
    arrivalTime: undefined,
    weightBillNo: undefined,
    billNo: undefined,
    containerNo: undefined,
    checked: undefined,
  }
  proxy.resetForm("formEditRef");
}

/** 取消按钮 */
function cancel() {
  dialogVisiable.value = false;
  reset();
}

defineExpose({
  viewData
})
</script>
<style scoped lang='scss'>
@import '../../assets/styles/variables.module.scss';

/** 动态对话框样式 */
.dy-dialog {
  grid-gap: 20px;

  :deep(.el-form-item__label) {
    height: 36px;
    text-align: center !important;
    line-height: 36px !important;
  }

  .dy-form {
    flex: 1 !important;

    :deep(.form) {
      width: 100% !important;
    }
  }

  .dy-footer {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .el-image-viewer__wrapper {
    right: 20%;
    left: 20%;
    height: auto;
    width: 60% !important;
    height: auto;
  }

  .el-image-viewer__mask {
    opacity: 0 !important;
  }

  .form-items {
    align-items: center !important;

    .form-input {
      height: 36px !important;
      width: 100%;
    }
  }

  .el-form-item--default {
    margin-bottom: 22px !important;
  }

  .model-value {
    display: inline-block;
    width: 100%;
    color: $--color-info;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .model-remark {
    line-height: 1.5;
    word-wrap: break-word !important;
    white-space: normal !important;
    display: -webkit-box !important;
    -webkit-box-orient: vertical !important;
    /* 子元素排列垂直排列 */
    -webkit-line-clamp: 5 !important;
    /* 设置从第几行后开始省略 */
    overflow: hidden;
  }

  // .no-model-value {
  //     font-size: 20px;
  // }
}

/** 表格图片展示样式 */
.el-image {
  background-color: $--color-bg-info !important;
  color: $--color-info !important;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    z-index: 2000;
  }
}
</style>